﻿using Microsoft.AspNetCore.Mvc;
using WZN_VoteSys.Models.Database;
using WZN_VoteSys.service;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using WZN_VoteSys.Models;
using System.Transactions;
using System;
using System.Collections.Generic;

namespace WZN_VoteSys.Controllers
{

    [Route("[controller]/[action]")]
    [ApiController]
    public class UpdateController : ControllerBase
    {
        private readonly IJWTService _jwtService;
        private readonly WZN_VoteSysContext _db;
        public UpdateController(IJWTService jwtService, WZN_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }

        /// <summary>
        /// 校验用户是否上传过该类别的投票项目（需授权） 输入：类别标识 输出：是或否
        /// </summary>
        /// <param name="Classid"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public string RepeatCheck(int Classid)
        {
            var Email = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            Entry entry = _db.Entrys.FirstOrDefault(x => x.Email == Email && x.Classid == Classid);
            if (entry == null)
            {
                return "该用户未上传过该类型投票项目";
            }
            else
            {
                return "该用户上传过该类型投票项目";
            }
        }

        /// <summary>
        /// 资料上传接口（需授权） 输入：投票项目信息、项目类别 输出：消息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public string Update(UpdateRequest request)
        {
            var Email = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            if (_db.Entrys.FirstOrDefault(x => x.Email == Email && x.Classid == request.classid) != null)
            {
                return "您提交过该类型的投票";
            }
            using (var tran = _db.Database.BeginTransaction())
            {
                try
                {
                    Enterprise enterprise=new Enterprise();
                    enterprise.Enterprisename = request.enterprisename;
                    enterprise.EnterpriseInfo = request.enterpriseInfo;
                    _db.Enterprises.Add(enterprise);
                    if (_db.SaveChanges() <= 0)
                    {
                        return "上传公司失败";
                    }
                    var enterpriseID = _db.Enterprises.FirstOrDefault(x => x.Enterprisename == request.enterprisename && x.EnterpriseInfo == request.enterpriseInfo).EnterpriseId;
                    var Award = request.AwardRequest.Select(x => new Award()
                    {
                        EnterpriseId = enterpriseID,
                        Classid = x.Classid,
                        AwardTypeId = x.AwardTypeID,
                        UpdateImg1 = x.UpdateImg1,
                        UpdateImg2 = x.UpdateImg2,
                        UpdateImg3 = x.UpdateImg3,
                        UpdateImg4 = x.UpdateImg4,
                        UpdateImg5 = x.UpdateImg5,
                    });
                    _db.Awards.AddRange(Award);
                    if (_db.SaveChanges()<=0)
                    {
                        return "上传奖项失败";
                    }
                    Entry entry = new Entry();
                    entry.Email = Email;
                    entry.Classid=request.classid;
                    entry.EnterpriseId = enterpriseID;
                    entry.Statues = 0;
                    _db.Entrys.Add(entry);
                    if (_db.SaveChanges() > 0)
                    {
                        tran.Commit();
                        return "上传投票成功";
                    }
                    else
                    {
                        return "上传投票失败";
                    }

                }
                    catch(Exception ex)
                {
                    return ex.ToString();
                }
            }
        }

        /// <summary>
        /// 审核资料接口 输入：投票项目Id、审核结果（通过、拒绝） 输出：消息
        /// </summary>
        /// <param name="entryID"></param>
        /// <param name="stauc"></param>
        /// <returns></returns>
        [HttpPost]
        public string Examine(int entryID,string stauc)
        {
            if (entryID ==0)
            {
                return "请输入正确的投票ID";
            }
            var entry = _db.Entrys.FirstOrDefault(x => x.EntryId == entryID);
            if (stauc == "通过")
            {
                entry.Statues = 1;
                if (_db.SaveChanges() > 0)
                {
                    return "修改审核状态成功";
                }
                else
                {
                    return "修改失败";
                }
            }
            if(stauc == "拒绝")
            {
                entry.Statues = 2;
                if(_db.SaveChanges() > 0){
                    return "修改审核状态成功";
                }
                else
                {
                    return "修改失败";
                }
            }
            else
            {
                return "请输入正确的状态";
            }
        }




        /// <summary>
        /// 获取企业详情（投票项目详情）信息接口 输入：投票项目Id 输出：所需内容字段
        /// </summary>
        /// <param name="EnrtyID"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult EnterpriseDetail(int EnrtyID)
        {
            var EnterpriseID=_db.Entrys.FirstOrDefault(x=>x.EntryId == EnrtyID).EnterpriseId;//获取企业编号
            if (EnterpriseID == 0)
            {
                return NotFound();
            }
            var enterp=_db.Enterprises.FirstOrDefault(x=>x.EnterpriseId == EnterpriseID);//获取企业信息
            if(enterp == null)
            {
                return NotFound();
            }
            //var data = _db.Awards.ToList();
            var groopDate = _db.Awards.Where(x => x.EnterpriseId == EnterpriseID).AsEnumerable()
                .GroupBy(x=>x.AwardTime.Substring(0,4))
                .Select(g=>new {Year=g.Key,Item=g.ToList()})
                .ToList();
            return Ok(groopDate);
        }
    }
}
